package com.hfengxiang.example.canvasrotatedemo;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.TypedValue;

public class Utils {
    private static Paint paint;

    static {
        paint = new Paint();
    }

    public static float dpToPixel(float dp) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                Resources.getSystem().getDisplayMetrics());
    }

    public static Bitmap getPhoto(Resources res, int width) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, R.drawable.vertical, options);
        options.inJustDecodeBounds = false;
        options.inDensity = options.outWidth;
        options.inTargetDensity = width;
        return BitmapFactory.decodeResource(res, R.drawable.photo, options);
    }

    public static void drawAxis(Canvas canvas, float width, float height, String message) {
        paint.setColor(Color.RED);
        canvas.drawLine(-width / 2f, 0, width / 2f, 0, paint);
        paint.setStrokeWidth(3);
        canvas.drawLine(width / 2f - 15, -15, width / 2f, 0, paint);
        canvas.drawLine(width / 2f - 15, 15, width / 2f, 0, paint);
        paint.setColor(Color.GREEN);
        paint.setStrokeWidth(1);
        canvas.drawLine(0, -height / 2f, 0, height / 2f, paint);
        paint.setStrokeWidth(3);
        canvas.drawLine(-15, height / 2f - 15, 0, height / 2f, paint);
        canvas.drawLine(15, height / 2f - 15, 0, height / 2f, paint);
        paint.setTextSize(40);
        paint.setColor(Color.RED);
        canvas.drawText(message, 40, 60, paint);
        paint.reset();
    }

    public static void drawCoordinate(Canvas canvas, int coordinatorX, int coordinatorY,
                                      boolean onTop) {
        int color = onTop ? Color.GREEN : Color.RED;
        paint.setTextSize(20);
        paint.setColor(color);
        canvas.drawCircle(coordinatorX, coordinatorY, 5, paint);
        int offsetY = onTop ? -40 : 40;
        canvas.drawText("(" + coordinatorX + "," + coordinatorY + ")",
                coordinatorX - 40, coordinatorY + offsetY, paint);
    }

    public static float[] getTranslateFromMatrix(Matrix matrix){
        float[] values = new float[9];
        matrix.getValues(values);
        return new float[]{values[2],values[5]};
    }
}
